package com.eightbears.beboy.ui.merchant.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.AddTagAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.PostFormBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.FileCallBack;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.image.circle.ClipImageActivity;
import com.eightbears.beboy.base.view.popupwindow.BottomSelectionPopup;
import com.eightbears.beboy.base.view.popupwindow.TagsPopup;
import com.eightbears.beboy.entity.ShopTechnicianEntity;
import com.eightbears.beboy.entity.SuccessEntity;
import com.eightbears.beboy.entity.TagsEntity;
import com.eightbears.beboy.entity.event.ImageBus;
import com.eightbears.beboy.entity.status.Status_Error;
import com.google.gson.Gson;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CACHE_HEAD_FILE;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_ADDSHOPTECHNICIAN_CODE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_UPDATESHOPTECHNICIAN;
import static com.eightbears.beboy.ui.merchant.activity.TechnicianManageActivity.PARAMS_TECHNICIANMANAGE;

public class AddTechnicianActivity extends BaseActivity {
    private static final int REQUEST_CAPTURE = 100;        //请求相机
    private static final int REQUEST_PICK = 101;          //请求相册
    private static final int REQUEST_CROP_PHOTO = 102;    //请求截图
    private File tempFile;
    private String cropImagePath;                         // 剪裁路径

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.et_num)
    EditText et_num;
    @BindView(R.id.et_account)
    EditText et_account;
    @BindView(R.id.et_age)
    EditText et_age;
    @BindView(R.id.et_height)
    EditText et_height;
    @BindView(R.id.et_weight)
    EditText et_weight;
    @BindView(R.id.et_bust)
    EditText et_bust;
    @BindView(R.id.et_waistline)
    EditText et_waistline;
    @BindView(R.id.et_hips)
    TextView et_hips;
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.rl_tags)
    RelativeLayout rl_tags;
    @BindView(R.id.sw)
    SwipeBackLayout sw;
    @BindView(R.id.rv_tags)
    RecyclerView rv_tags;

    private ShopTechnicianEntity.DataBean.ListBean mListBean;
    private File mCoverfile;
    private File mCropImagePathFile = new File("");
    private String mUrl;
    private ArrayList<Integer> listTags = new ArrayList<>();
    private ArrayList<TagsEntity.DataBean> editListTags = new ArrayList<>();
    private ArrayList<Integer> editTagsId = new ArrayList<>();
    private String status;
    private AddTagAdapter mAddTagAdapter;


    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_technician);
        initView();
        initData();
        initEvent();
    }


    @Override
    protected void initView() {
        ButterKnife.bind(this);
        mListBean = (ShopTechnicianEntity.DataBean.ListBean) getIntent().getExtras().get(PARAMS_TECHNICIANMANAGE);
        rv_tags.setLayoutManager(new GridLayoutManager(mContext, 3));
        mAddTagAdapter = new AddTagAdapter(mContext);
        KLog.e(mListBean);
        if (null != mListBean) {
            initEdit();
        } else {
            initAdd();
        }
    }

    private void initAdd() {
        status = "1";
        tv_title.setText("添加技师");
        mUrl = URL_ADDSHOPTECHNICIAN_CODE + SPUtil.getUser().getData().getShops().get(0).getShop_id() + "/girls";
        KLog.e("mCoverfile" + mCoverfile);
    }

    private void initEdit() {
        status = "2";
        tv_title.setText("编辑技师");
        mUrl = URL_UPDATESHOPTECHNICIAN + mListBean.getId();
        String cover = mListBean.getCover();
        KLog.e(cover);
        if (null != cover && !(cover.equals(""))) {
            Glide.with(mContext).load(cover).
                    into((ImageView) iv_head);
            downImage(cover);
            mCoverfile = new File(cover);
        }
        String user_id = mListBean.getUser_id();
        if (TextUtils.isEmpty(user_id)) {
            et_account.setText("");
        } else {
            et_account.setText(String.valueOf(mListBean.getUser_id()));
        }

        et_num.setText(String.valueOf(mListBean.getNo()));
        et_age.setText(String.valueOf(mListBean.getAge()));
        et_height.setText(String.valueOf(mListBean.getHeight()));
        et_weight.setText(String.valueOf(mListBean.getWeight()));
        et_bust.setText(String.valueOf(mListBean.getBust()));
        et_waistline.setText(String.valueOf(mListBean.getWaistline()));
        et_hips.setText(String.valueOf(mListBean.getHips()));

        List<ShopTechnicianEntity.DataBean.ListBean.TagsBean> tags = mListBean.getTags();

        for (int i = 0; i < tags.size(); i++) {
            TagsEntity.DataBean dataBean = new TagsEntity.DataBean();
            dataBean.setBg_color(mListBean.getTags().get(i).getBg_color());
            dataBean.setText_color(mListBean.getTags().get(i).getText_color());
            dataBean.setTag_id(mListBean.getTags().get(i).getTag_id());
            dataBean.setName(mListBean.getTags().get(i).getName());
            editTagsId.add(mListBean.getTags().get(i).getTag_id());
            editListTags.add(dataBean);
        }
        mAddTagAdapter.setNewData(editListTags);
        rv_tags.setAdapter(mAddTagAdapter);

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {
        sw.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.rl_tags)
    void tags() {
//        startLocalActivity((Activity) mContext, TechnicianTagsActivity.class);
        final TagsPopup tagsPopup = new TagsPopup(this);
        tagsPopup.showPopupWindow();
        tagsPopup.setOnClickItemListener(new TagsPopup.OnClickItemListener() {
            @Override
            public void onClickItem(ArrayList<TagsEntity.DataBean> list, View v) {
                editListTags.clear();
                tagsPopup.dismiss();
                mAddTagAdapter.setNewData(list);
                rv_tags.setAdapter(mAddTagAdapter);

                for (int i = 0; i < list.size(); i++) {
                    listTags.add(list.get(i).getTag_id());
                }


            }
        });
    }

    @OnClick(R.id.btn_send)
    void btn() {
        postData();
    }

    @OnClick(R.id.iv_head)
    void head() {
        showImageDialog();
    }

    /**
     * 添加数据
     */
    public void postData() {
        KLog.e("mCoverfile" + mCoverfile);
        if (null != mCoverfile)
            mCropImagePathFile = mCoverfile;

        if (null != cropImagePath) {
            mCropImagePathFile = new File(cropImagePath);
        } else {
            if (null == mCoverfile) {
                ShowToast.showShortToast("请选择技师照片");
                return;
            }
        }
//        if (String.valueOf(mCropImagePathFile).contains("http:")){
//            T.getInstance().CenterShort("请选择技师图片");
//            return;
//        }
        KLog.e("图片路径" + cropImagePath);
        KLog.e("图片路径2" + mCropImagePathFile);
        String num = et_num.getText().toString();
        String account = et_account.getText().toString();
        String age = et_age.getText().toString();
        String height = et_height.getText().toString();
        String weight = et_weight.getText().toString();
        String bust = et_bust.getText().toString();
        String waistline = et_waistline.getText().toString();
        String hips = et_hips.getText().toString();

        if (null == mCropImagePathFile) {
            ShowToast.showShortToast("请选择技师头像");
            return;
        }

        if (TextUtils.isEmpty(num)) {
            ShowToast.showShortToast("请输入技师号码");
            return;
        }

        if (TextUtils.isEmpty(age)) {
            ShowToast.showShortToast("请输入年龄");
            return;
        }

        if (TextUtils.isEmpty(height)) {
            ShowToast.showShortToast("请输入身高");
            return;
        }

        if (TextUtils.isEmpty(weight)) {
            ShowToast.showShortToast("请输入体重");
            return;
        }

        if (TextUtils.isEmpty(bust)) {
            ShowToast.showShortToast("请输入胸围");
            return;
        }
        if (TextUtils.isEmpty(waistline)) {
            ShowToast.showShortToast("请输入腰围");
            return;
        }
        if (TextUtils.isEmpty(hips)) {
            ShowToast.showShortToast("请输入臀围");
            return;
        }

        if (editListTags.size() == 0 && listTags.size() == 0) {
            ShowToast.showShortToast("请选择标签");
            return;
        }

        PostFormBuilder builder = OkHttpUtils.post();//创建请求构建器
        builder.url(mUrl);
        builder.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        builder.addParams("user_id", account);
        builder.addParams("no", num);
        builder.addFile("cover", "cover", mCropImagePathFile);
        builder.addParams("age", age);
        builder.addParams("height", height);
        builder.addParams("weight", weight);
        builder.addParams("bust", bust);
        builder.addParams("waistline", waistline);
        builder.addParams("hips", hips);

        if (listTags.size() > 0) {
            builder.addParams("tags", new Gson().toJson(listTags));
        } else {
            builder.addParams("tags", new Gson().toJson(editTagsId));
        }

        builder.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);

                if (status == "1") {
                    ShowToast.showShortToast("添加失败");
                } else if (status == "2") {
                    ShowToast.showShortToast("编辑失败");
                }
            }

            @Override
            public void onResponse(String response) {
                KLog.e(response);
                try {
                    //json解析获取是实例对象
                    SuccessEntity successEntity = GsonUtil.fromJson(response, SuccessEntity.class);
                    //判断是否登陆成功 200
                    if (null != successEntity && successEntity.getStatus_code() == 200) {
                        if (status == "1") {
                            ShowToast.showShortToast("添加成功");
                        } else if (status == "2") {
                            ShowToast.showShortToast("编辑成功");
                        }
                        EventBus.getDefault().post(new ImageBus("refresh_addTechnician"));
                        //关闭
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void showImageDialog() {
        BottomSelectionPopup bottomSelectionPopup = new BottomSelectionPopup((Activity) mContext);
        bottomSelectionPopup.setTxCancel(getResources().getString(R.string.btn_cancel));
        bottomSelectionPopup.setTx_1Text(getResources().getString(R.string.text_select_image));
        bottomSelectionPopup.setTx_2Text(getResources().getString(R.string.text_select_capture));
        bottomSelectionPopup.setOnClickItemListener(new BottomSelectionPopup.OnClicktemListener() {
            @Override
            public void onClickItem(View v) {
                switch (v.getId()) {
                    case R.id.ll_1:
                        selectPicture();
                        break;
                    case R.id.ll_2:
                        getCapture();
                        break;
                }
            }
        });
        bottomSelectionPopup.showPopupWindow();
    }

    private void selectPicture() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
    }

    private void getCapture() {
        //创建拍照存储的图片文件
        tempFile = new File(checkDirPath(CACHE_HEAD_FILE), System.currentTimeMillis() + ".jpg");
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        startActivityForResult(intent, REQUEST_CAPTURE);
    }


    /**
     * 检查文件是否存在
     */
    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CAPTURE:
                if (resultCode == RESULT_OK) {
                    gotoClipActivity(Uri.fromFile(tempFile));
                }
                break;
            case REQUEST_PICK:
                if (null != data) {
                    Uri pickUri = data.getData();
                    gotoClipActivity(pickUri);
                }

                break;
            case REQUEST_CROP_PHOTO:
                if (resultCode == RESULT_OK) {
                    Uri cropUri = data.getData();
                    if (cropUri == null) {
                        return;
                    }
                    cropImagePath = getRealFilePathFromUri(getApplicationContext(), cropUri);
                    CommonUtils.loadImageView(mContext, cropImagePath, R.mipmap.icon_jishi_def, iv_head);
                }
                break;
        }
    }

    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, ClipImageActivity.class);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
    }

    /**
     * 根据Uri返回文件绝对路径, file:///开头的 和 content://开头的情况
     */
    public static String getRealFilePathFromUri(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 通过网络下载图片
     */
    private void downImage(String mCover) {
        String s = System.currentTimeMillis() + "_";
        OkHttpUtils.get().url(mCover).build().execute(new FileCallBack(CACHE_HEAD_FILE, s + 5) {
            @Override
            public void inProgress(float progress) {

            }

            @Override
            public void onError(Call call, Exception e) {
                ShowToast.showShortToast("请选择技师图片");
                KLog.e(e.getMessage());
            }

            @Override
            public void onResponse(File response) {
                mCoverfile = response;
                KLog.e(response);
            }
        });
    }
}
